/**
 * @Description:租户列表
 * @Author: CHEHSHUANG
 * @Date: 2019/1/23
 */
import React, {Component} from 'react';
import {Checkbox, message} from "antd"
import {connect} from "react-redux"
import EditTenantModal from "./EditTenantModal";
import SimpleTable from "../../../commons/components/SimpleTable";
import {listAllTenant, save} from "./TenantService";
import {hide, show} from "../../../configs/SharedReducer";
import ToolBar from "../../../commons/components/toolbar/ToolBar";
import {searchListByKey, searchListByKeyWithTag} from "../../../commons/utils/CommonUtils";
import ConfigTenantModal from "./ConfigTenantModal";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import PageOperateHoc from "../../../commons/components/PageOperateHoc";
import CheckAuth from "../../../commons/components/CheckAuth";

class TenantTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      confirmLoading: false,
      isEdit: false,
      editData: null,
      visible: false,
      configVisible: false,
      selectedRows: [],
      dataSource: [],
      searchData: false,//本地查询操作
      searchValue: ""
    }
  }

  getFormRef = (ref) => {
    this.formRef = ref;
  }
  getConfigFormRef = (ref) => {
    this.configFormRef = ref;
  }

  componentDidMount() {
    this.getDataSource()
  }

  getDataSource = () => {
    this.props.show();
    listAllTenant().then(dataSource => {
      this.setState({dataSource, selectedRows: [],searchData: false})
    }).catch(e => {
    }).finally(() => {
      this.props.hide();
    })
  };

  onSelectRow = (selectedRows) => {
    this.setState({selectedRows})
  };

  handleConfig = (record) => {
    // if (this.checkOnlyOneSelect()) {
    this.setState({editData: record});
    this.setConfigModalVisible(true);
    // }
  }
  handleAdd = () => {
    this.setModalVisible(true);
  }
  handleEdit = (record) => {
    // if (this.checkOnlyOneSelect()) {
    this.setState({editData: record});
    this.setModalVisible(true, true);
    // }
  }
  //保存租戶
  handleSave = () => {
    const saveData = this.formRef.getFormValue();
    if (saveData) {
      this.setState({confirmLoading: true});
      save(saveData).then(res => {
        if(res&&res.status==="SUCCESS"){
          message.success(res.message || "保存成功");
          this.setModalVisible(false);
          this.setState({searchValue: ""});
          this.getDataSource();
        }else{
          message.error(res.message || "保存失败");
        }

      }).catch(e => {
      }).finally(() => {
        this.setState({confirmLoading: false});
      })
    }
  }
  handleQuickValueChange = (e) => {
    if(!e.target||!e.target.value){
      this.setState({searchValue:""},()=>this.getDataSource());
    }else{
      this.setState({searchValue:e.target.value||""});
    }
  }
  handleQuickSearch = (searchValue) => {
    searchListByKeyWithTag(this.state.dataSource, {keyword: searchValue}, ['code', 'name']).then(dataSource => {
      this.setState({dataSource, searchValue,searchData: true})
    })
  }
  getColumns = () => {
    return [
      {
        title: "操作",
        width: 120,
        dataIndex: "operator",
        render: (text, record, index) => {
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <CheckAuth operateCode="BASIC-ZFGL-ZHGL-SAVE" key="edit">
                <a className={'row-operator-item'} onClick={() => this.handleEdit(record)}>编辑</a>
              </CheckAuth>
              <CheckAuth operateCode="BASIC-ZFGL-ZHGL-CONFIG" key="config">
                <a className={'row-operator-item'} onClick={() => this.handleConfig(record)}>配置</a>
              </CheckAuth>
            </div>
          )
        }
      },
      {
        title: "代码",
        width: 100,
        dataIndex: "code"
      },
      {
        title: "名称",
        width: 200,
        dataIndex: "name"
      },
      {
        title: "冻结",
        width: 100,
        dataIndex: "frozen",
        align: "center",
        render: (text, record, index) => {
          return <Checkbox
            disabled={true}
            checked={text}
          />
        }
      }
    ];
  }

  setModalVisible = (visible, isEdit = false) => {
    let newState = {visible};
    if (visible) {
      newState.isEdit = isEdit;
    }
    this.setState(newState);
  };
  setConfigModalVisible = (configVisible) => {
    let newState = {configVisible};
    this.setState(newState);
  };
  searchBtnCfg = () => {
    return {
      quickSearchCfg: {
        style: {width: 250},
        placeholder: "输入代码或名称查询",
        allowClear: true,
        value: this.state.searchValue,
        onChange: (v)=>this.handleQuickValueChange(v),
        onSearch: (v) => {
          this.handleQuickSearch(v)
        }
      }
    }
  }
  btnsCfg = () => {
    return [
      {
        title: "新增",
        checkRight: true,
        operateCode: "BASIC-ZFGL-ZHGL-SAVE",
        propsCfg: {
          type: "primary",
          onClick: () => {
            this.handleAdd()
          }
        }
      },
      // {
      //     title: "编辑",
      //     checkRight: true,
      //     propsCfg: {
      //         onClick: () => {
      //             this.handleEdit()
      //         }
      //     }
      // },
      // {
      //     title: "配置",
      //     checkRight: true,
      //     propsCfg: {
      //         onClick: () => {
      //             this.handleConfig()
      //         }
      //     }
      // }
    ]
  }
  //选择行判断
  checkOnlyOneSelect = () => {
    const {selectedRows} = this.state;
    if (selectedRows.length === 0) {
      message.error('请选择一行数据！');
      return false;
    }
    if (selectedRows.length > 1) {
      message.error('只能选择一行数据！');
      return false;
    }
    return true;
  };

  render() {
    const {dataSource, selectedRows, searchValue, searchData, visible, editData, isEdit, configVisible} = this.state;
    const title = isEdit ? "编辑租户" : "新增租户";
    const configTitle = editData ? `配置【${editData.name}】基础数据` : "";
    return (
      <HeadBreadcrumb>
        <ToolBar
          btnsCfg={this.btnsCfg()}
          searchBtnCfg={this.searchBtnCfg()}
        />
        <SimpleTable
          checkBox={false}
          data={searchData ? dataSource.filter(item=>item.tag === true) : dataSource}
          columns={this.getColumns()}
          rowsSelected={selectedRows}
          onSelectRow={this.onSelectRow}
        />
        {
          visible && <EditTenantModal
            title={title}
            confirmLoading={this.state.confirmLoading}
            visible={visible}
            isEdit={isEdit}
            editData={editData}
            onRef={this.getFormRef}
            onOk={this.handleSave}
            onCancel={() => this.setModalVisible(false)}
          />
        }
        {
          configVisible && <ConfigTenantModal
            title={configTitle}
            visible={configVisible}
            editData={editData}
            onCancel={() => this.setConfigModalVisible(false)}
          />
        }
      </HeadBreadcrumb>
    );
  }
}

const mapStateToProps = (state) => {
  return {};
};
const mapDispatchToProps = {hide, show};
export default connect(mapStateToProps, mapDispatchToProps)(PageOperateHoc(TenantTable));
